package com.ktjy.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ktjy.dto.DictDTO;
import com.ktjy.pojo.SysDictType;
import com.ktjy.service.SysDictTypeService;
import com.ktjy.utils.AjaxResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/sys/dictType")
@Tag(name="字典类型模块")
@Slf4j
public class SysDictTypeController {
    @Autowired
    private SysDictTypeService sysDictTypeService;

    /**
     * 字典类型列表接口
     * @param dictDTO
     * @param pageNo
     * @param pageSize
     * @return
     */
    @RequestMapping("/list")
    @Operation(summary="字典类型列表接口")
    public AjaxResult list(DictDTO dictDTO,
                           @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
                           @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize){
        IPage<SysDictType> page = sysDictTypeService.findPage(dictDTO, pageNo, pageSize);
        return AjaxResult.success(page);
    }

    /**
     * 字典类型保存接口
     * @param sysDictType
     * @return
     */
    @PostMapping("/save")
    @Operation(summary="字典类型保存接口")
    public AjaxResult saveOrUpdate(@RequestBody SysDictType sysDictType){
        try {
            sysDictTypeService.saveOrUpdateDict(sysDictType);
            return AjaxResult.success("保存成功");
        } catch (Exception e) {
            log.error("SysDictTypeController中saveOrUpdate方法执行报错的。",e);
            return AjaxResult.error("保存失败");
        }
    }

    /**
     * 字典类型删除接口
     * @param params
     * @return
     */
    @PostMapping("/del")
    @Operation(summary="字典类型删除接口")
    public AjaxResult del(@RequestBody Map<String, Long[]> params){
        Long[] dictIds = params.get("dictId");
        if (dictIds != null && dictIds.length > 0) {
            sysDictTypeService.delBatchDict(dictIds);
            return AjaxResult.success("删除成功");
        }
        return AjaxResult.error("删除失败");
    }

    /**
     * 字典类型详情接口
     * @param id
     * @return
     */
    @GetMapping("/view/{id}")
    @Operation(summary="字典类型详情接口")
    public AjaxResult view(@PathVariable("id") Long id){
        try {
            SysDictType sysDictType = sysDictTypeService.findDict(id);
            if (sysDictType != null){
                return AjaxResult.success(sysDictType);
            }
        } catch (Exception e) {
            log.error("SysDictTypeController中view方法执行报错的。",e);
        }
        return AjaxResult.success();
    }

    /**
     * 字典类型导出接口
     * @param dictDTO
     * @param response
     */
    @GetMapping("/export")
    @Operation(summary = "字典类型导出接口")
    public void exportExcel(DictDTO dictDTO, HttpServletResponse response){
        //查询需要导出的数据
        List<SysDictType> list = sysDictTypeService.findList(dictDTO);
        //生成一个Excel工作簿对象
        Workbook workbook = sysDictTypeService.exportExcel("字典类型数据", list);
        //设置HTTP响应头信息，指定内容类型为Excel文件
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        //创建输出流对象
        OutputStream out = null;
        try {
            //设置下载文件的名称和下载方式
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("字典类型数据", "utf-8") + ".xlsx");
            //获取输出流对象
            out = response.getOutputStream();
            //将数据写出到响应的输出流中
            workbook.write(out);
        } catch (Exception e) {
            log.error("SysDictTypeController中exportExcel方法执行报错的。",e);
            throw new RuntimeException(e);
        } finally {
            if (out != null){
                try {
                    out.close();
                    workbook.close();
                } catch (IOException e) {
                    log.error("SysDictTypeController中exportExcel方法执行报错的。",e);
                }
            }
        }

    }

}
